using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using NetProtocol.POD;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public class UIFormation : UIBaseWindow
    {
        /// <summary>
        /// 静态配置
        /// </summary>
        private static UICreateConfig _createConfig = new()
        {
            prefabName = nameof(UIFormation),
            layer = EUILayer.Normal,
            isFullScreen = true,
        };

        /// <summary>
        /// 创建UI的配置
        /// </summary>
        public override IUICreateConfig createConfig => _createConfig;

        #region Template Generate,don't modify
        protected partial class UIB_UIFormation
        {
            #region ObjectBinding Generate 
            public IQIGame.Onigao.Framework.ExButton btn_SetDefaultForm { protected set; get; }
            public IQIGame.Onigao.Framework.ExButton btn_Edit { protected set; get; }
            public IQIGame.Onigao.Framework.ExButton btn_SetCaptain { protected set; get; }
            public IQIGame.Onigao.Framework.ExButton btn_SwitchAttribute { protected set; get; }
            public GameObject topLeftBack { protected set; get; }
            public GameObject formationSoulCell { protected set; get; }
            public GameObject fightPower { protected set; get; }
            public IQIGame.Onigao.Framework.ExText textFormId { protected set; get; }
            public IQIGame.Onigao.Framework.ExText textFormName { protected set; get; }
            public GameObject descRoot { protected set; get; }
            public GameObject defaultEnabling { protected set; get; }
            public UnityEngine.UI.ExLoopHorizontalScrollRect loopHorizontalScrollRect { protected set; get; }
            public virtual void InitBinding(ObjectBinding __binding)
            {
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExButton>("btn_SetDefaultForm", out var __tbv0);
                this.btn_SetDefaultForm = __tbv0;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExButton>("btn_Edit", out var __tbv1);
                this.btn_Edit = __tbv1;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExButton>("btn_SetCaptain", out var __tbv2);
                this.btn_SetCaptain = __tbv2;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExButton>("btn_SwitchAttribute", out var __tbv3);
                this.btn_SwitchAttribute = __tbv3;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("topLeftBack", out var __tbv4);
                this.topLeftBack = __tbv4;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("formationSoulCell", out var __tbv5);
                this.formationSoulCell = __tbv5;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("fightPower", out var __tbv6);
                this.fightPower = __tbv6;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExText>("textFormId", out var __tbv7);
                this.textFormId = __tbv7;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExText>("textFormName", out var __tbv8);
                this.textFormName = __tbv8;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("descRoot", out var __tbv9);
                this.descRoot = __tbv9;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("defaultEnabling", out var __tbv10);
                this.defaultEnabling = __tbv10;
                __binding.TryGetVariableValue<UnityEngine.UI.ExLoopHorizontalScrollRect>("loopHorizontalScrollRect", out var __tbv11);
                this.loopHorizontalScrollRect = __tbv11;
            }


            #endregion ObjectBinding Generate 
        }
        #endregion Template Generate,don't modify

        #region fields & properties
        UIN_CommonTitleValue formDesc = null;
        UIN_CommonTitleValue formFightPower = null;
        LoopScrollAdapter<UIN_FormationTab> tabs = null;
        ListScrollAdapter<UIN_FormationSoulCell> forms = null;

        FormationData formData = null;
        int indexSelectedTab = -1;
        bool isShowAttr = false;
        bool isSetCaptain = false;

        protected UIB_UIFormation ui { get; set; }
        private UIMsgDispatcher currMsgDispatcher => this._msgDispatcher as UIMsgDispatcher;
        #endregion

        protected override void BeforeInit()
        {
            ui = new UIB_UIFormation();
            ui.InitBinding(this.csObjBind);
        }

        protected override void AddMsgListeners()
        {
            currMsgDispatcher.AddListener<FormationPOD>(MsgEventType.OneFormationChanged, this.OnMsgOneFormationChanged);
        }

        void OnMsgOneFormationChanged(FormationPOD formationPOD)
        {
            if (this.formData == null || this.formData.formId != formationPOD.formId)
                return;
            this.OnViewFormation();
        }

        protected override void OnInit()
        {
            this.tabs = this.InitLoopScroll<UIN_FormationTab>(this.ui.loopHorizontalScrollRect, this.OnTabChanged);
            this.tabs.InitUnitSelected(UnitSelectType.ByExToggle, this.OnTabSelected);
            this.forms = this.InitListScroll<UIN_FormationSoulCell>(this.ui.formationSoulCell, this.OnFormChanged);
            this.forms.InitUnitSelected(UnitSelectType.None, this.OnFormSelected);

            this.formDesc = this.InitChildNode<UIN_CommonTitleValue>(this.ui.descRoot);
            this.formFightPower = this.InitChildNode<UIN_CommonTitleValue>(this.ui.fightPower);

            this.ui.btn_Edit.onClick.AddListener(this.OnClickEdit);
            this.ui.btn_SetCaptain.onClick.AddListener(this.OnClickSetCaptain);
            this.ui.btn_SetDefaultForm.onClick.AddListener(this.OnClickSetDefaultForm);
            this.ui.btn_SwitchAttribute.onClick.AddListener(this.OnClickSwitchAttribute);

            var topLeftBack = this.InitChildNode<UIN_TopLeftBack>(this.ui.topLeftBack);
            topLeftBack.Show();
        }

        protected override void OnShow()
        {

        }

        protected override void OnHide()
        {

        }

        protected override void OnDispose()
        {
            this.formData = null;
            this.indexSelectedTab = -1;
            this.isShowAttr = false;
            this.isSetCaptain = false;
        }

        protected override void OnShow(UIBaseData data)
        {
            UD_Formation d = (UD_Formation)data;
            this.indexSelectedTab = d.tabIndex;
            this.ViewFromTab();
        }

        void ViewFromTab()
        {
            int cntForm = APIUIFormation.FormMaxCount;
            int selectForm = this.indexSelectedTab;
            if (selectForm == -1)
                selectForm = (GameDataCenter.PlayerData.formation.defFormId - 1);
            this.tabs.RefillCellsInfiniteAndSelected(cntForm, selectForm);
        }

        void OnTabChanged(UIN_FormationTab item, int index)
        {
            var objData = FormationModule.Instance.GetFormationByIndex(index);
            item.Show(objData);
        }

        void OnTabSelected(int index, UIN_FormationTab item)
        {
            this.isSetCaptain = false;
            this.isShowAttr = false;
            this.indexSelectedTab = index;

            this.ViewFormation(item);
        }

        void OnFormChanged(UIN_FormationSoulCell item, int index)
        {
            int pos = APIUIFormation.GetFormHeroPosByIndex(index);
            var posData = this.formData.GetFormationHeroData(pos);
            item.Show(posData, this.isShowAttr, this.isSetCaptain);
        }

        void OnFormSelected(int index, UIN_FormationSoulCell item)
        {
            int pos = APIUIFormation.GetFormHeroPosByIndex(index);
            var posData = this.formData.GetFormationHeroData(pos);

            if (!posData.isHasHero)
            {
                var cid = APIUIFormation.GetTipNoticeCid4BtnClick(3);
                NoticeModule.ShowNoticeNoCall(cid);
                return;
            }
            if (!posData.isRegularHeroPos)
            {
                var cid = APIUIFormation.GetTipNoticeCid4BtnClick(4);
                NoticeModule.ShowNoticeNoCall(cid);
                return;
            }
            if (posData.isCaptain)
            {
                return;
            }
            this.SendSetCaptain(posData.belong.formId, posData.cid).Forget();
        }

        async UniTaskVoid SendSetCaptain(int formId, int heroCid)
        {
            var result = await FormationModule.NetCore.CS_setCaptain(formId, heroCid);
            if (result.IsSuccess)
            {
                this.OnViewFormCells();
            }
        }

        void ViewFormation(UIN_FormationTab tab = null)
        {
            int tabIndex = tab.tabIndex;
            this.formData = FormationModule.Instance.GetFormationByIndex(tabIndex);
            this.OnViewFormation();
        }

        void OnViewFormation()
        {
            if (this.formData == null)
            {
                return;
            }
            this.ui.textFormId.text = this.formData.formId + "-";
            this.ui.textFormName.text = FormationModule.Instance.GetFormationName(this.formData);

            this.formFightPower.Show(this.formData.fightPower.ToString());

            this.OnViewDefalutInfo();
            this.OnViewFormCells();
        }

        void OnViewDefalutInfo()
        {
            bool isDefault = FormationModule.Instance.IsDefaultFormation(this.formData.formId);
            this.ui.btn_SetDefaultForm.SetActive(!isDefault);
            this.ui.defaultEnabling.SetActive(isDefault);

            string strValue = APIUIFormation.GetStrFormUsedState(isDefault);
            this.formDesc.Show(strValue);
        }

        void OnViewFormCells()
        {
            int cnt = APIUIFormation.FormHeroAllCount;
            int selectedIndex = -1;
            if (this.isSetCaptain)
            {
                for (int i = 1; i <= APIUIFormation.FormRegularHeroCount; i++)
                {
                    var form = this.formData.GetFormationHeroData(i);
                    if (form.cid != 0 && form.cid == this.formData.captainHeroCid)
                    {
                        selectedIndex = i - 1;
                        break;
                    }
                }
            }
            this.forms.RefillCells(cnt, selectedIndex);
        }

        void OnClickEdit()
        {
            this.OpenUI<UIFormationEditName>(UIFormationEditName.CreateUIData(this.indexSelectedTab));
        }

        void OnClickSetCaptain()
        {
            if (this.formData.heroCountInForm <= 0)
            {
                return;
            }
            this.isSetCaptain = !this.isSetCaptain;
            this.forms.selectedType = this.isSetCaptain ? UnitSelectType.ByExButton : UnitSelectType.None;
            this.OnViewFormCells();
        }

        void OnClickSetDefaultForm()
        {
            int formId = this.formData.formId;
            bool isHasHero = FormationModule.Instance.IsHasRegularHero(formId);
            if (!isHasHero)
            {
                var cid = APIUIFormation.GetTipNoticeCid4BtnClick(1);
                NoticeModule.ShowNoticeNoCall(cid);
                return;
            }
            this.SendSetDefaultFrom(formId).Forget();
        }

        async UniTaskVoid SendSetDefaultFrom(int formId)
        {
            var result = await FormationModule.NetCore.CS_setDefault(formId);
            if (result.IsSuccess)
            {
                this.ViewFromTab();
            }
        }

        void OnClickSwitchAttribute()
        {
            if (this.formData.heroCountInForm <= 0)
            {
                return;
            }
            this.isShowAttr = !this.isShowAttr;
            this.OnViewFormCells();
        }

        protected override UIBaseData OnGetLeaveData()
        {
            UD_Formation d = ClassPool<UD_Formation>.Get();
            d.tabIndex = this.indexSelectedTab;
            return d;
        }
    }
}
